package com.example.sangong.utils;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.websocket.Session;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 维护客户端websocket的关系
 */
@Component
@Slf4j
public class WebSocketRelationUtils {
    public static final Map<String, Session> sessionMap = new ConcurrentHashMap<>();
    @Autowired
    private RedissonUtils redissonUtils;

    @Value("${server.port}")
    private String port;


    private static final String WEBSOCKET_RELATION_KEY = "WEBSOCKET_RELATION_KEY";

    /**
     * 添加websocket关系到redis中
     *
     * @param userId
     */
    public void addRelation(String userId) {
        String ip = null;
        try {
            ip = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            log.info("获取ip地址异常");
            throw new RuntimeException(e);
        }
        String url = String.format("http://%s:%s/sangong/person/sendMessage", ip, port);

        redissonUtils.hset(WEBSOCKET_RELATION_KEY, userId, url);
    }

    /**
     * 删除websocket关系到redis中
     *
     * @param userId
     */
    public void removeRelation(String userId) {
        redissonUtils.hdel(WEBSOCKET_RELATION_KEY, userId);
    }

    /**
     * 删除websocket关系到redis中
     *
     * @param userId
     */
    public String getRelation(String userId) {
        String hget = redissonUtils.hget(WEBSOCKET_RELATION_KEY, userId);
        if (StrUtil.isBlank(hget)) {
            return null;
        }
        return hget.split("-")[0];
    }

    /**
     * 删除websocket关系到redis中
     */
    public     Map<String,String>  getAllRelation() {
        return redissonUtils.hgetAll(WEBSOCKET_RELATION_KEY);

    }

}
